# encoding: utf-8
import requests
from time import sleep
import json
import sys
import re

sys.setrecursionlimit(1000000)

err = 0


def main(e, g, key):
    global err
    global b
    if len(g) == 2:
        e2 = ''
        e1 = g[0] + g[1]
        e3 = g[1]
    else:
        e2 = g[2]
        e3 = g[2]
        e1 = g[0] + g[1]
    print(key)
    print(g)
    r = requests.get('http://api.map.baidu.com/place/v2/search?query=' + key + e2 + '&region=' + e1 +
                     '&city_limit=true&scope=2&output=json&page_size=20&page_num=0&ak=T60T8EFOGWmGev3bCaedp3yBWFu8ryYH').text
    f = json.loads(r)
    try:
        num = (int(f['total']) // 20)
    except:
        print(f)
        return main(e, g, key)
    if int(f['total']) <= 20:
        num = 1
    print('++', 'http://api.map.baidu.com/place/v2/search?query=' + key + e2
          + '&region=' + e1 + '&city_limit=true&scope=2&output=json&page_size=20&page_num=0&ak=T60T8EFOGWmGev3bCaedp3yBWFu8ryYH')
    for i in range(0, num):
        r1 = requests.get(
            'http://api.map.baidu.com/place/v2/search?query=' + key + e2 + '&region=' + e1 + '&city_limit=true&scope=2&output=json&page_size=20&page_num=' + str(
                i) + '&ak=T60T8EFOGWmGev3bCaedp3yBWFu8ryYH').text
        f1 = json.loads(r1)
        # try:
        #     f=len(f1['results'])
        # except:
        # print('==',f1)
        # re
        if err >= 3:
            input('=-=-')
        try:
            o = f1['results']
        except:
            err += 1
            if err < 3:
                return main(e, g, key)
        if len(f1['results']) == 0:
            continue
        for j in f1['results']:
            try:
                tag = j['detail_info']['tag']
            except Exception as pp:
                tag = '暂无'
            print(j['name'], e3, key, j['uid'], tag)
    print("===================" * 5)


if __name__ == '__main__':
    # print(url_list())
    s = []
    for g in open('city1.txt'):
        s.append(g.strip())
    for i in s[1030:]:
        h = i.split(':')
        main(i, h, '礼品')
